<?php
/**
 * Created by PhpStorm.
 * User: yangxu
 * Date: 2016/5/19
 * Time: 12:17
 */

namespace Home\Controller;
use Think\Controller;

class QuestionController extends Controller{
    var $catArr=array();
    /******分类列表*******/
    public function catList(){
        $parent_id=isset($_POST['parent_id'])?trim($_POST['parent_id']):0;
        $userId=isset($_POST['userId'])?trim($_POST['userId']):0;
        $type=isset($_POST['type'])?trim($_POST['type']):1;
        $status=isset($_POST['status'])?trim($_POST['status']):1;
        $model=M('Category');
		//'parent_id='.$parent_id.'&type='.$type
		$w['parent_id']=$parent_id;
		$w['type']=$type;
        $catlist=$model->where($w)->select();
        foreach ($catlist as $key => $val){
            switch ($status){
                case 1:
                    $quesli=ComputeController::getExamNum($val['id'],$type);
                    $recordli=ComputeController::getRecordNum($val['id'],$type,$userId);
                    $catlist[$key]['num']=(int)$quesli['num'];
                    $catlist[$key]['status']=$quesli['status'];
                    $catlist[$key]['right']=(int)$recordli['right'];
                    $catlist[$key]['wrong']=(int)$recordli['wrong'];
                    $catlist[$key]['totals']=$recordli['totals'];
                    break;
                case 2:
                    $numli=ComputeController::getCollectNum($val['id'],$type, $userId);
                    $catlist[$key]['num']=(int)$numli['num'];
                    $catlist[$key]['status']=$numli['status'];
                    break;
                case 3:
                    $numli=ComputeController::getWrongNum($val['id'],$type, $userId);
                    $catlist[$key]['num']=(int)$numli['num'];
                    $catlist[$key]['status']=$numli['status'];
                    break;
            }
            
        }
        if(empty($catlist)){
            $requset=array('returnCode'=>999,'returnMsg'=>'空数据','returnData'=>null);
        }else{
            $requset=array('returnCode'=>0,'returnMsg'=>'返回成功','returnData'=>$catlist);
        }

        echo json_encode($requset); exit;
    }
    /***********默认分类***********/
    public function mainCatList(){
        $model=M('Category');
        $catlist=$model->where('parent_id=0')->select();
        foreach ($catlist as $key => $val){
            $cattwo=$model->where('parent_id='.$val['id'])->select();
            foreach ($cattwo as $keys => $vals){
                if($vals['parent_id'] != 0){
                    $numli=ComputeController::getExamNum($vals['id'],1);
                    $cattwo[$keys]['num']=$numli['num'];
                }
            }
            $catlist[$key]['two']=$cattwo;
        }
        if(empty($catlist)){
            $requset=array('returnCode'=>999,'returnMsg'=>'空数据','returnData'=>null);
        }else{
            $requset=array('returnCode'=>0,'returnMsg'=>'返回成功','returnData'=>$catlist);
        }
        echo json_encode($requset); exit;
    }
    /*********章节练习*******/
    public function questionList(){
        $catId=isset($_POST['catId'])?trim($_POST['catId']):0;    //分类ID
        $userId=isset($_POST['userId'])?trim($_POST['userId']):0;    //分类ID
        $page=isset($_POST['page'])?trim($_POST['page']):1;       //页码
        $res=$this->freeSetInc($catId, $userId);
        if($res == 0){
            $requset=array('returnCode'=>997,'returnMsg'=>'免费做题数已用完');
        }else{
            $model=M('Questions'); //数据表
            $where=array(
                'cat_id'     =>     $catId,
            );
            $questionList=$model->where($where)->order('id')->page($page,1)->select();
            if(empty($questionList)){
                $requset=array('returnCode'=>999,'returnMsg'=>'空数据','returnData'=>null);
            }else{
                foreach($questionList as $k => $v){
                    $questionList[$k]['options']=json_decode($v['options'],true);
                }
                $requset=array('returnCode'=>0,'returnMsg'=>'返回成功','returnData'=>$questionList);
            }
        }
        echo json_encode($requset);exit;
    }
    /*********真题模考**********/
    public function examList(){
        $catId=isset($_POST['catId'])?trim($_POST['catId']):0;    //分类ID
        $userId=isset($_POST['userId'])?trim($_POST['userId']):0;    //分类ID
        $page=isset($_POST['page'])?trim($_POST['page']):1;       //页码
        $res=$this->freeSetInc($catId, $userId);
        if($res == 0){
            $requset=array('returnCode'=>997,'returnMsg'=>'免费做题数已用完');
        }else{
            $model=M('Exam');                                    //数据表
            $where=array(
                'cat_id'     =>     $catId,
            );
            $questionList=$model->where($where)->order('id')->page($page,1)->select();
            if(empty($questionList)){
                $requset=array('returnCode'=>999,'returnMsg'=>'空数据');
            }else {
                foreach ($questionList as $k => $v) {
                    $questionList[$k]['options'] = json_decode($v['options'], true);
                }
                $requset = array('returnCode' => 0, 'returnMsg' => '返回成功', 'returnData' => $questionList);
            }
        }
        echo json_encode($requset); exit;
    }
    /**********错题记录*********/
    public function wrong(){
        $questionId=isset($_POST['questionId'])?trim($_POST['questionId']):null;    //分类ID
        $userID=isset($_POST['userId'])?trim($_POST['userId']):null;       //页码
        $catId=isset($_POST['catId'])?trim($_POST['catId']):null;       //页码
        $type=isset($_POST['type'])?trim($_POST['type']):1;       //页码
        if(empty($userID) || empty($questionId) || empty($catId)){
            $requset=array(
                'returnCode' => 998,
                'returnMsg' => '参数错误'
            );
            echo json_encode($requset); exit;
        }
        if($type == 1){
            $model=M('Wrong_section');
            $data=array(
                'user_id'=>$userID,
                'questions_id'=>$questionId,
                'cat_id'=>$catId,
                'addtime'=>time()
            );
        }else{
            $model=M('Wrong_exam');
            $data=array(
                'user_id'=>$userID,
                'exam_id'=>$questionId,
                'cat_id'=>$catId,
                'addtime'=>time()
            );
        }
        if($model->add($data)){
            $requset=array('returnCode'=>0,'returnMsg'=>'成功');
        }else{
            $requset=array('returnCode'=>999,'returnMsg'=>'失败');
        }
        echo json_encode($requset);exit;
    }
    /************添加笔记*************/
    public function noteAdd(){
        $questionId=isset($_POST['questionId'])?trim($_POST['questionId']):null;    //分类ID
        $userID=isset($_POST['userId'])?trim($_POST['userId']):null;       //页码
        $type=isset($_POST['type'])?trim($_POST['type']):null;       //页码
        $content=isset($_POST['content'])?trim($_POST['content']):null;       //页码
        if(empty($userID) || empty($questionId) || empty($content)){
            $requset=array(
                'returnCode' => 998,
                'returnMsg' => '参数错误'
            );
            echo json_encode($requset); exit;
        }
        if($type == 1){
            $model=M('note_section');
            $data=array(
                'user_id'=>$userID,
                'questions_id'=>$questionId,
                'content'=>$content,
                'addtime'=>time());
        }else{
            $model=M('note_exam');
            $data=array(
                'user_id'=>$userID,
                'exam_id'=>$questionId,
                'content'=>$content,
                'addtime'=>time());
        }

        if($model->add($data)){
            $requset=array('returnCode'=>0,'returnMsg'=>'成功');
        }else{
            $requset=array('returnCode'=>999,'returnMsg'=>'失败');
        }
        echo json_encode($requset); exit;
    }
    /************笔记列表**************/
    public function noteList(){
        $questionId=isset($_POST['questionId'])?trim($_POST['questionId']):null;    //分类ID
        $userID=isset($_POST['userId'])?trim($_POST['userId']):null;       //页码
        $type=isset($_POST['type'])?trim($_POST['type']):1;       //页码
        $page=isset($_POST['page'])?trim($_POST['page']):1;       //页码
        if ($type == 1){
            $model=M('Note_section');
            if(!empty($userID)){
                $where[C('DB_PREFIX').'note_section.user_id']=$userID;
            }
            $where[C('DB_PREFIX').'note_section.questions_id']=$questionId;
            $notelist=$model->field(C('DB_PREFIX').'note_section.*,'.C('DB_PREFIX').'user.nickname,'.C('DB_PREFIX').'user.avatar')
                ->join(C('DB_PREFIX').'user ON '.C('DB_PREFIX').'user.id='.C('DB_PREFIX').'note_section.user_id')
                ->where($where)->page($page,5)->select();
        }else{
            $model=M('Note_exam');
            if(!empty($userID)){
                $where[C('DB_PREFIX').'note_exam.user_id']=$userID;
            }
            $where[C('DB_PREFIX').'note_exam.exam_id']=$questionId;
            $notelist=$model->field(C('DB_PREFIX').'note_exam.*,'.C('DB_PREFIX').'user.nickname,'.C('DB_PREFIX').'user.avatar')
                ->join(C('DB_PREFIX').'user ON '.C('DB_PREFIX').'user.id='.C('DB_PREFIX').'note_exam.user_id')
                ->where($where)->page($page,5)->select();
        }
        if(empty($notelist)){
            $requset=array('returnCode'=>999,'returnMsg'=>'空数据','returnData'=>null);
        }else{
            $requset=array('returnCode'=>0,'returnMsg'=>'返回成功','returnData'=>$notelist);
        }

        echo json_encode($requset); exit;
    }
    /*************错题练习**************/
    public function wrongList(){
        $userID=isset($_POST['userId'])?trim($_POST['userId']):null;       //页码
        $catId=isset($_POST['catId'])?trim($_POST['catId']):null;       //页码
        $type=isset($_POST['type'])?trim($_POST['type']):1;       //页码
        $page=isset($_POST['page'])?trim($_POST['page']):1;       //页码
        if($type == 1){
            $model=M('Wrong_section');
            $where[C('DB_PREFIX').'wrong_section.user_id']=$userID;
            $where[C('DB_PREFIX').'wrong_section.cat_id']=$catId;
            $wronglist=$model->field(C('DB_PREFIX').'questions.*,'.C('DB_PREFIX').'wrong_section.id as wrongId')
                ->join(C('DB_PREFIX').'questions ON '.C('DB_PREFIX').'questions.id='.C('DB_PREFIX').'wrong_section.questions_id')
                ->where($where)->page($page,1)->select();
        }else{
            $model=M('Wrong_exam');
            $where[C('DB_PREFIX').'wrong_exam.user_id']=$userID;
            $where[C('DB_PREFIX').'wrong_exam.cat_id']=$catId;
            $wronglist=$model->field(C('DB_PREFIX').'exam.*,'.C('DB_PREFIX').'wrong_exam.id as wrongId')
                ->join(C('DB_PREFIX').'exam ON '.C('DB_PREFIX').'exam.id='.C('DB_PREFIX').'wrong_exam.exam_id')
                ->where($where)->page($page,1)->select();
        }
        foreach ($wronglist as $k => $v) {
            $wronglist[$k]['options'] = json_decode($v['options'], true);
        }
        if(empty($wronglist)){
            $requset=array('returnCode'=>999,'returnMsg'=>'空数据','returnData'=>null);
        }else{
            $requset=array('returnCode'=>0,'returnMsg'=>'返回成功','returnData'=>$wronglist);
        }

        echo json_encode($requset); exit;
    }
    /************删除错题************/
    public function wrongDel(){
        $userID=isset($_POST['userId'])?trim($_POST['userId']):null;
        $type=isset($_POST['type'])?trim($_POST['type']):1;
        $wrongId=isset($_POST['wrongId'])?trim($_POST['wrongId']):null;
        if($type == 1){
            $model=M('Wrong_section');
        }else{
            $model=M('Wrong_exam');
        }
        if($model->where(array('user_id'=>$userID,'id'=>$wrongId))->delete()){
            $requset=array('returnCode'=>0,'returnMsg'=>'成功');
        }else{
            $requset=array('returnCode'=>999,'returnMsg'=>'失败');
        }
        echo json_encode($requset); exit;
    }
    /***********题目纠错************/
    public function redress(){
        $userID=isset($_POST['userId'])?trim($_POST['userId']):null;       //页码
        $status=isset($_POST['status'])?trim($_POST['status']):null;       //页码
        $questionId=isset($_POST['questionId'])?trim($_POST['questionId']):null;       //页码
        $content=isset($_POST['content'])?trim($_POST['content']):null;       //页码
        $type=isset($_POST['type'])?trim($_POST['type']):1;       //页码
        if($type == 1){
            $model=M('Correct_section');
            $data=array(
                'questions_id'    =>     $questionId,
                'user_id'         =>     $userID,
                'status'          =>     $status,
                'content'         =>     $content,
                'addtime'         =>     time()
            );
        }else{
            $model=M('Correct_exam');
            $data=array(
                'exam_id'         =>     $questionId,
                'user_id'         =>     $userID,
                'status'          =>     $status,
                'content'         =>     $content,
                'addtime'         =>     time()
            );
        }
        if($model->add($data)){
            $requset=array('returnCode'=>0,'returnMsg'=>'成功');
        }else{
            $requset=array('returnCode'=>999,'returnMsg'=>'失败');
        }
        echo json_encode($requset); exit;
    }
    /***********添加收藏***********/
    public function collectAdd(){
        $userID=isset($_POST['userId'])?trim($_POST['userId']):null;       //用户Id
        $questionId=isset($_POST['questionId'])?trim($_POST['questionId']):null;       //题目Id
        $type=isset($_POST['type'])?trim($_POST['type']):1;       //题目Id
        $catId=isset($_POST['catId'])?trim($_POST['catId']):1;       //题目Id
        if($type == 1){
            $model=M('Collect_section');
            $data=array(
                'user_id'=>$userID,
                'questions_id'=>$questionId,
                'cat_id'=>$catId,
                'addtime'=>time()
            );
        }else{
            $model=M('Collect_exam');
            $data=array(
                'user_id'=>$userID,
                'exam_id'=>$questionId,
                'cat_id'=>$catId,
                'addtime'=>time()
            );
        }
        if($model->add($data)){
            $requset=array('returnCode'=>0,'returnMsg'=>'成功');
        }else{
            $requset=array('returnCode'=>999,'returnMsg'=>'失败');
        }
        echo json_encode($requset); exit;
    }
    /*************收藏练习*************/
    public function collectList(){
        $userID=isset($_POST['userId'])?trim($_POST['userId']):null;       //页码
        $catId=isset($_POST['catId'])?trim($_POST['catId']):null;       //页码
        $type=isset($_POST['type'])?trim($_POST['type']):null;       //页码
        $page=isset($_POST['page'])?trim($_POST['page']):1;       //页码
        //$where['user_id']=$userID;
        //$where['cat_id']=$catId;
        if($type == 1){
			$where[C('DB_PREFIX').'collect_section.user_id']=$userID;
            $where[C('DB_PREFIX').'collect_section.cat_id']=$catId;
            $model=M('Collect_section');
            $collectlist=$model->field(C('DB_PREFIX').'questions.*,'.C('DB_PREFIX').'collect_section.id as collectId')
                ->join(C('DB_PREFIX').'questions ON '.C('DB_PREFIX').'questions.id='.C('DB_PREFIX').'collect_section.questions_id')
                ->where($where)->page($page,1)->select();
        }else{
			$where[C('DB_PREFIX').'collect_exam.user_id']=$userID;
            $where[C('DB_PREFIX').'collect_exam.cat_id']=$catId;
            $model=M('Collect_exam');
            $collectlist=$model->field(C('DB_PREFIX').'exam.*,'.C('DB_PREFIX').'collect_exam.id as collectId')
                ->join(C('DB_PREFIX').'exam ON '.C('DB_PREFIX').'exam.id='.C('DB_PREFIX').'collect_exam.exam_id')
                ->where($where)->page($page,1)->select();
        }
        foreach ($collectlist as $k => $v) {
            $collectlist[$k]['options'] = json_decode($v['options'], true);
        }
        if(empty($collectlist)){
            $requset=array('returnCode'=>999,'returnMsg'=>'空数据','returnData'=>null);
        }else{
            $requset=array('returnCode'=>0,'returnMsg'=>'返回成功','returnData'=>$collectlist);
        }
        echo json_encode($requset); exit;
    }
    /*************取消收藏***************/
    public function collectDel(){
        $userID=isset($_POST['userId'])?trim($_POST['userId']):null;       //用户id
        $type=isset($_POST['type'])?trim($_POST['type']):null;       //用户id
        $id=isset($_POST['collectId'])?trim($_POST['collectId']):null;       //页码
        if($type == 1){
            $model=M('Collect_section');
        }else{
            $model=M('Collect_exam');
        }

        if($model->where(array('user_id'=>$userID,'id'=>$id))->delete()){
            $requset=array('returnCode'=>0,'returnMsg'=>'成功');
        }else{
            $requset=array('returnCode'=>999,'returnMsg'=>'失败');
        }
        echo json_encode($requset); exit;
    }
    /***********做题记录*************/
    public function record(){
        $catId=isset($_POST['catId'])?trim($_POST['catId']):0;    //分类ID
        $userId=isset($_POST['userId'])?trim($_POST['userId']):0;    //用户ID
        $type=isset($_POST['type'])?trim($_POST['type']):0;    //用户ID
        if($type == 1){
            $model=M('Record_section');
        }else{
            $model=M('Record_exam');
        }

        $data=array(
            'cat_id'  =>   $catId,
            'user_id' =>    $userId
        );
        $cz=$model->where($data)->count();
        if($cz < 1){
            $model->add($data);
        }
        $model->where($data)->setInc('rights');
        $requset=array('returnCode'=>0,'returnMsg'=>'成功');
        echo json_encode($requset); exit;
    }
    /**
     * @param $cId
     * @param $userId
     * @return int
     */
    public function freeSetInc($cId,$userId){

        $free=M('Free');$quesOrder=M('Questions_order');
        $catId=$this->getCatId($cId);
        $orderli=$quesOrder->where(array('user_id'=>$userId,'cat_id'=>$catId,'status' => 1))->find();
        if(!empty($orderli)){
            $request=1;
        }else{
            $freeli=$free->field('total')->where(array('user_id'=>$userId,'cat_id'=>$catId))->find();
            if(empty($freeli)){
                $totalli=D('Category')->field('total')->where('id='.$catId)->find();
                $free->add(array('user_id'=>$userId,'cat_id'=>$catId,'total'=>$totalli['total']));
                $freeli=$free->field('total')->where(array('user_id'=>$userId,'cat_id'=>$catId))->find();
            }
            if((int)$freeli['total'] > 0){
                $free->where(array('cat_id'=>$catId,'user_id'=>$userId))->setDec('total');
                $request=1;
            }else{
                $request=0;
            }

        }
        return $request;
    }

    /**
     * @param $catId
     * @return mixed
     */
    public function getCatId($catId){
        $cat=M('Category');
        $catli=$cat->where('id='.$catId)->find();
        if($catli['level'] == 2){
            $cat_id=$catli['id'];
        }else{
            return $this->getCatId($catli['parent_id']);
        }
        return $cat_id;
    }
}